<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="com.oreilly.servlet.multipart.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<jsp:useBean id="utilities" class="masterpiece.util.Utilities" scope="session" />    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Uploading file to database</title>
<link rel="stylesheet" type="text/css" href="css/default.css" />
</head>
<body>
<%@ include file="top_menu.jsp" %>
  
  <%
  	try {
  		MultipartParser parser = new MultipartParser(request, Integer.MAX_VALUE);
  		
  		String      alt     = null;
  		String      credit  = null;
  		int         article = -1;
  		InputStream small   = null;
  		InputStream large   = null;
  		ArrayList<Byte> smallBuffer = null;
  		ArrayList<Byte> largeBuffer = null;
  		
  		Part p = parser.readNextPart();
  		
  		while (p != null) {
  			String name = p.getName();
  			if (name.equals("alt")) {
  				alt = ((ParamPart)p).getStringValue();
  			} else if (name.equals("credit")) {
  				credit = ((ParamPart)p).getStringValue();
  			} else if (name.equals("article")) {
  				article = Integer.parseInt(((ParamPart)p).getStringValue());
  			} else if (name.equals("small")) {
  				InputStream stream = ((FilePart)p).getInputStream();
  				smallBuffer = new ArrayList<Byte>(stream.available());
  				int b = stream.read();
  				while (b != -1) {
  					smallBuffer.add((byte)b);
  					b = stream.read();
  				}
  			} else if (name.equals("large")) {
  				InputStream stream = ((FilePart)p).getInputStream();
  				largeBuffer = new ArrayList<Byte>(stream.available());
  				int b = stream.read();
  				while (b != -1) {
  					largeBuffer.add((byte)b);
  					b = stream.read();
  				}
  			}
  			p = parser.readNextPart();
  		}
  		
  		byte[] smallBytes = new byte[smallBuffer.size()];
  		for (int i = 0; i < smallBytes.length; i++) {
  			smallBytes[i] = smallBuffer.get(i);
  		}
  		
  		byte[] largeBytes = new byte[largeBuffer.size()];
  		for (int i = 0; i < largeBytes.length; i++) {
  			largeBytes[i] = largeBuffer.get(i);
  		}
  		
  		small = new ByteArrayInputStream(smallBytes);
  		large = new ByteArrayInputStream(largeBytes);
  		
  	    utilities.insertPicture(article,
    		                   alt,
    			               credit,
    			               small,
    			               large);
  	   
  	    out.print("<p class=\"message success\">Picture uploaded successfully.</p>");
    } catch (Exception e) {
    	out.print("<p class=\"message error\">Error: "+e.getMessage()+"</p>");
    }%>
</body>
</html>